//
//  YLSignViewController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/9/18.
//  Copyright © 2017年 she1323. All rights reserved.
//  签到

#import "YLSignViewController.h"
#import "JTCalendar.h"
#import "YLGlobeHeader.h"
#import "YLSignRuleView.h"
#import "WHNetworkTool.h"
#import "YLAccountTool.h"
#import "WHProgressHUD.h"
#import "YLSignItem.h"
#import "YLMineViewModel.h"
#import "YLMyInfoModel.h"
@interface YLSignViewController ()<JTCalendarDelegate, UIScrollViewDelegate>
{
    NSMutableDictionary *_eventsByDate;
    
    NSMutableArray *_datesSelected;
    BOOL _selectionMode;
}

@property (strong, nonatomic) JTCalendarManager *calendarManager;
@property (weak, nonatomic) IBOutlet JTHorizontalCalendarView *calendarContentView;
@property (weak, nonatomic) IBOutlet JTCalendarMenuView *calendarMenuView;
// 积分总额
@property (weak, nonatomic) IBOutlet UILabel *totalPointLabel;
// 连续登录天数
@property (weak, nonatomic) IBOutlet UILabel *continuousLogindDayLabel;

@property (nonatomic, strong) NSMutableArray *months;

@property (nonatomic, strong) YLMineViewModel *viewModel;

@end

@implementation YLSignViewController

- (YLMineViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YLMineViewModel alloc] init];
    }
    return _viewModel;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"签到";
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    self.view.backgroundColor = [UIColor orangeColor];

   _calendarManager = [JTCalendarManager new];
    
    _calendarManager.delegate = self;
//
    [self createRandomEvents];
//
    _calendarManager.settings.weekDayFormat = JTCalendarWeekDayFormatSingle;
//
    [_calendarManager setMenuView:_calendarMenuView];
    _calendarContentView.backgroundColor = YLColor(244, 248, 248);
    [_calendarManager setContentView:_calendarContentView];
    _calendarContentView.delegate = self;
    [_calendarManager setDate:[NSDate date]];

    _datesSelected = [NSMutableArray new];

    _selectionMode = NO;
    
   
    [self loadData];
    
    [self loadData:[NSDate date]];
}

- (void)loadData
{
    __weak typeof(self) weakSelf = self;
    [[self.viewModel.myInfoCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        
        weakSelf.totalPointLabel.text = [NSString stringWithFormat:@"%zd", weakSelf.viewModel.myInfoModel.pointQuota];
        weakSelf.continuousLogindDayLabel.text = weakSelf.viewModel.myInfoModel.continuitySignDay;
    }];

}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    for (NSDate *date in self.months) {
        // 如果是同一个月，不加载
        if ([self.calendarManager.dateHelper date:date isTheSameMonthThan:_calendarContentView.date]) {
            return;
        }
        
    }
    [self loadData:_calendarContentView.date];
}

- (void)loadData:(NSDate *)date
{
    __weak typeof(self) weakSelf = self;
    NSString *url = [NSString stringWithFormat:@"%@AppCommon/GetCustomerSignLog", YLURL];
    
    [[WHNetworkTool shareInstance] cancel];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *nowDateStr = [dateFormatter stringFromDate:date];
    
    NSDictionary *param = @{@"MouthIndex" : nowDateStr};
    
    [[WHNetworkTool shareInstance] sendPostWithUrl:url header:[YLAccountTool header] params:param success:^(id responseObject) {
        if ([responseObject[@"httpCode"] integerValue] == 200) {
            
            [weakSelf.months addObject:date];
            
            YLSignItem *item = [YLSignItem yy_modelWithDictionary:responseObject[@"httpResult"]];
        
            for (YLSignModel *model in item.item) {
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
               
                if (model.signDate.length > 18) {
                    model.signDate = [[model.signDate stringByReplacingOccurrencesOfString:@"T" withString:@" "] substringToIndex:18];
                    NSDate *date1 = [dateFormatter dateFromString:model.signDate];
                    
                    if (date1 == nil) {
                        break ;
                    }
                    
                    [_datesSelected addObject:date1];
                }
                [weakSelf.calendarManager reload];
            }
            
        } else {
            [WHProgressHUD showError:responseObject[@"message"]];
        }
    } fail:^(NSError *error) {
    }];
}

- (NSMutableArray *)months
{
    if (!_months) {
        _months = [NSMutableArray array];
    }
    return _months;
}


#pragma mark - Buttons callback

- (IBAction)didSelectionModeTouch
{
    _selectionMode = !_selectionMode;
    
    if(_selectionMode){
        [_datesSelected removeAllObjects];
        [_calendarManager reload];
    }
}

#pragma mark - CalendarManager delegate

- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
    // Today
    if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
         dayView.circleView.hidden = YES;
       // dayView.signView.hidden = YES;
        dayView.whiteView.backgroundColor = [UIColor orangeColor];
         dayView.circleView.backgroundColor = [UIColor blueColor];
        dayView.dotView.backgroundColor = [UIColor blackColor];
        //dayView.textLabel.textColor = [UIColor whiteColor];
    } else {
       dayView.whiteView.backgroundColor = [UIColor whiteColor];
    }
    // Selected date
    if([self isInDatesSelected:dayView.date]){
        // dayView.circleView.hidden = NO;
        dayView.signView.hidden = NO;
        // dayView.circleView.backgroundColor = [UIColor redColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
         dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Other month
    else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        //  dayView.circleView.hidden = YES;
        dayView.signView.hidden = YES;
        //  dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor lightGrayColor];
    }
    // Another day of the current month
    else{
        //  dayView.circleView.hidden = YES;
        dayView.signView.hidden = YES;
        //  dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
}

- (BOOL)isTodayWithDate:(NSDate *)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear;
    
    // 1.获得当前时间的年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
    
    // 2.获得self的年月日
    NSDateComponents *selfCmps = [calendar components:unit fromDate:date];
    return
    (selfCmps.year == nowCmps.year) &&
    (selfCmps.month == nowCmps.month) &&
    (selfCmps.day == nowCmps.day);
}




- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
  //  [self isTodayWithDate:calendar.date]
    
    __weak typeof(self) weakSelf = self;
    if(_selectionMode && _datesSelected.count == 1 && ![_calendarManager.dateHelper date:[_datesSelected firstObject] isTheSameDayThan:dayView.date]){
        [_datesSelected addObject:dayView.date];
        [self selectDates];
        _selectionMode = NO;
        [_calendarManager reload];
        return;
    }
    
    if (![self isTodayWithDate:dayView.date]) {
        // 不是今天
        return;
    } else {
        
        // 判断下今天有没有签到过
        if([self isInDatesSelected:dayView.date]){
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"今天已经签到过，不可重复签到" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确   定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            [action setValue:YLLOrgColor forKey:@"_titleTextColor"];
            [alertController addAction:action];
            
            [weakSelf presentViewController:alertController animated:YES completion:nil];
            return;
        }
    }
    
    // 判断有没有选中，加入移除选中数组
    if([self isInDatesSelected:dayView.date]){
        [_datesSelected removeObject:dayView.date];
        
        [UIView transitionWithView:dayView
                          duration:.3
                           options:0
                        animations:^{
                            [weakSelf.calendarManager reload];
                            dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
                        } completion:nil];
    }
    else{
        NSString *url = [NSString stringWithFormat:@"%@AppCommon/CostomerSign", YLURL];
        
        [[WHNetworkTool shareInstance] sendPostWithUrl:url header:[YLAccountTool header] params:nil success:^(id responseObject) {
            // 请求成功
            if ([responseObject[@"httpCode"] integerValue] == 200) {
                [weakSelf loadData];
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"签到成功，获得5积分" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确   定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                }];
                [action setValue:YLLOrgColor forKey:@"_titleTextColor"];
                [alertController addAction:action];
                
                [weakSelf presentViewController:alertController animated:YES completion:nil];
            } else {
    
                [WHProgressHUD showError:responseObject[@"message"]];
            }
        } fail:^(NSError *error) {
            
        }];
        
        
        [_datesSelected addObject:dayView.date];
        
        dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
        [UIView transitionWithView:dayView
                          duration:.3
                           options:0
                        animations:^{
                            [weakSelf.calendarManager reload];
                            dayView.circleView.transform = CGAffineTransformIdentity;
                        } completion:nil];
    }
    
    if(_selectionMode) {
        return;
    }
    
    // Don't change page in week mode because block the selection of days in first and last weeks of the month
    if(_calendarManager.settings.weekModeEnabled){
        return;
    }
    
    // Load the previous or next page if touch a day from another month
    
    if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
            [_calendarContentView loadNextPageWithAnimation];
        }
        else{
            [_calendarContentView loadPreviousPageWithAnimation];
        }
    }
}

#pragma mark - Date selection

- (BOOL)isInDatesSelected:(NSDate *)date
{
    for(NSDate *dateSelected in _datesSelected){
        if([_calendarManager.dateHelper date:dateSelected isTheSameDayThan:date]){
            return YES;
        }
    }
    
    return NO;
}

- (void)selectDates
{
    NSDate * startDate = [_datesSelected firstObject];
    NSDate * endDate = [_datesSelected lastObject];
    
    if([_calendarManager.dateHelper date:startDate isEqualOrAfter:endDate]){
        NSDate *nextDate = endDate;
        while ([nextDate compare:startDate] == NSOrderedAscending) {
            [_datesSelected addObject:nextDate];
            nextDate = [_calendarManager.dateHelper addToDate:nextDate days:1];
        }
    }
    else {
        NSDate *nextDate = startDate;
        while ([nextDate compare:endDate] == NSOrderedAscending) {
            [_datesSelected addObject:nextDate];
            nextDate = [_calendarManager.dateHelper addToDate:nextDate days:1];
        }
    }
}

#pragma mark - Fake data

#pragma mark - Views customization

- (UIView *)calendarBuildMenuItemView:(JTCalendarManager *)calendar
{
    UILabel *label = [UILabel new];
    
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"Avenir-Medium" size:16];
    
    return label;
}

- (void)calendar:(JTCalendarManager *)calendar prepareMenuItemView:(UILabel *)menuItemView date:(NSDate *)date
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"yyyy年MMMM";
        
        dateFormatter.locale = _calendarManager.dateHelper.calendar.locale;
        dateFormatter.timeZone = _calendarManager.dateHelper.calendar.timeZone;
    }
    
    menuItemView.text = [dateFormatter stringFromDate:date];
}

- (UIView<JTCalendarWeekDay> *)calendarBuildWeekDayView:(JTCalendarManager *)calendar
{
    JTCalendarWeekDayView *view = [JTCalendarWeekDayView new];
    
    for(UILabel *label in view.dayViews){
        label.textColor = [UIColor blackColor];
        label.font = [UIFont fontWithName:@"Avenir-Light" size:14];
    }
    
    return view;
}

- (UIView<JTCalendarDay> *)calendarBuildDayView:(JTCalendarManager *)calendar
{
    JTCalendarDayView *view = [JTCalendarDayView new];
    
    view.textLabel.font = [UIFont fontWithName:@"Avenir-Light" size:13];
    
    view.circleRatio = .8;
    view.dotRatio = 1. / .9;
    
    return view;
}

#pragma mark - Fake data

// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"dd-MM-yyyy";
    }
    
    return dateFormatter;
}

- (BOOL)haveEventForDay:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    
    if(_eventsByDate[key] && [_eventsByDate[key] count] > 0){
        return YES;
    }
    
    return NO;
    
}

- (void)createRandomEvents
{
    _eventsByDate = [NSMutableDictionary new];
    
    for(int i = 0; i < 30; ++i){
        // Generate 30 random dates between now and 60 days later
        NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
        
        // Use the date as key for eventsByDate
        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        
        if(!_eventsByDate[key]){
            _eventsByDate[key] = [NSMutableArray new];
        }
        
        [_eventsByDate[key] addObject:randomDate];
    }
}
- (IBAction)signInRole:(UIButton *)sender {
    YLSignRuleView *rule = [[YLSignRuleView alloc] init];
    rule.frame = [UIScreen mainScreen].bounds;
    [[UIApplication sharedApplication].keyWindow addSubview:rule];
}

- (void)dealloc
{
   // NSLog(@"销毁");
}

@end
